import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

import 'package:get/get.dart';

import '../../bean/UserInfo.dart';
import '../../manager/AppSetInfoManager.dart';
import '../../manager/UserInfoManager.dart';
import '../../network/Api.dart';
import '../../network/ResultData.dart';
import '../../utils/toast_utils.dart';
import '../../utils/utils.dart';
import '../main/main_view.dart';
import '../main/main_view_ipad.dart';
import '../web/WebViewPage.dart';
import 'login_state.dart';

class LoginLogic extends GetxController {
  final LoginState state = LoginState();
  late TextEditingController userName, password;

  @override
  void onInit() {
    super.onInit();
    userName = TextEditingController();
    // mfy001 topnet

    // 13683371178 topnet123
    // 15638250508 xn123456
    // 15038357107 topnet123
    // userName = TextEditingController(text: '13683371178');
    password = TextEditingController();
    // password = TextEditingController(text: "topnet123");
  }

  @override
  void onReady() {
    super.onReady();
  }

  // 登录
  void login() async {
    if (!state.isSelected.value) {
      return toast.show("请阅读并同意《用户服务协议》和《隐私政策》");
    }

    if (userName.text.isEmpty) {
      return toast.show("请输入手机号或者账号");
    }

    if (userName.text.isEmpty) {
      return toast.show("请输入密码");
    }

    postLogin().then((value) {
      if (value) {
        if (isPad(Get.context!)) {
          Get.off(const MainPageIpad(title: "首页"));
        } else {
          Get.off(const MainPage(title: "首页"));
        }
      }
    });
  }

  // 密码登录接口
  Future<bool> postLogin() async {
    Map<String, dynamic> param = {
      'appCode': UserInfoManager().getAppCode(),
      'tenantId': UserInfoManager().getTenantId(),
      "platType": 1,
      "loginName": userName.text,
      "loginPassword": password.text,
      "loginType": 1
    };
    ResultData resultData = await Api.login(param);
    if (resultData.isSuccess) {
      state.userInfo = UserInfo.fromJson(resultData.data["data"]);
      if (state.userInfo != null) {
        UserInfoManager().setUserInfo(state.userInfo);
        return true;
      }
      return true;
    }
    toast.show(resultData.data["message"]);
    return false;
  }

  @override
  void onClose() {
    super.onClose();
  }

  /// 跳转 用户协议和隐私政策
  void goToWebViewPage() {
    Get.to(() => WebViewPage(title: '用户协议和隐私政策', url: AppSetInfoManager().getAgreementUrl()));
  }
}
